﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace JenkinsCodeBuid.Service
{
    public static class RestClientHelper
    {
        /// <summary>
        /// Post数据
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<T> PostData<T>(string postUrl, object entity)
        {
            try
            {
                var client = new RestClient();
                client.DefaultParameters.Clear();
                IRestRequest request = new RestRequest(postUrl, Method.POST, DataFormat.Json);
                request.AddParameter("Accept", "application/json, text/javascript, */*; q=0.01", ParameterType.HttpHeader);
                request.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
                //request.AddParameter("invalid", "f821de3a2131465a8b46d888eb043cf5", ParameterType.HttpHeader);
                request = request.AddJsonBody(entity);
                var response = await client.ExecuteTaskAsync<T>(request);
                if (response.StatusCode == HttpStatusCode.OK && response.Data == null)
                {
                    if(typeof(T)==typeof(string))
                    {
                        return (T)((object)response.Content);
                    }
                }
                if (!response.IsSuccessful)
                {
                }
                return response.Data;
            }
            catch (Exception e)
            {
                return default;
            }
        }
        /// <summary>
        /// Post数据(图片)
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<byte[]> PostDataImg(string postUrl, object entity)
        {
            try
            {
                var client = new RestClient();
                client.DefaultParameters.Clear();
                IRestRequest request = new RestRequest(postUrl, Method.POST, DataFormat.Json);
                request.AddParameter("Accept", "application/json, text/javascript, */*; q=0.01", ParameterType.HttpHeader);
                request.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
                //request.AddParameter("invalid", "f821de3a2131465a8b46d888eb043cf5", ParameterType.HttpHeader);
                request = request.AddJsonBody(entity);
                var response = client.Post(request);
                //if (response.ContentType == "image/jpeg")
                //{
                //    return response.Content;
                //}
                return response.RawBytes;
            }
            catch (Exception e)
            {
                return default;
            }
        }
        /// <summary>
        ///// Post From数据
        ///// </summary>
        ///// <param name="postUrl"></param>
        ///// <param name="obj"></param>
        ///// <returns></returns>
        //public static async Task<T> PostFormData<T>(string postUrl, object obj)
        //{
        //    try
        //    {
        //        var client = new RestClient();
        //        client.DefaultParameters.Clear();
        //        IRestRequest request = new RestRequest(postUrl + "?" + FormatUrl(obj), Method.POST);
        //        //IRestRequest request = new RestRequest(postUrl, Method.POST);
        //        request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
        //        var response = await client.ExecuteTaskAsync<T>(request);
        //        return response.Data;
        //    }
        //    catch (Exception e)
        //    {
        //        return default;
        //    }
        //}
        /// <summary>
        /// Get数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="getUrl"></param>
        /// <returns></returns>
        public static async Task<T> GetData<T>(string getUrl, string token = "")
        {
            try
            {
                var client = new RestClient(getUrl);
                var request = new RestRequest(Method.GET);
                if (!string.IsNullOrWhiteSpace(token))
                {
                    request.AddParameter("Authorization", "Bearer " + token, ParameterType.HttpHeader);
                }
                var response = await client.ExecuteTaskAsync<T>(request);
                return response.Data;
            }
            catch (Exception e)
            {
                return default;
            }
        }
        /// <summary>
        /// Get数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="getUrl"></param>
        /// <returns></returns>
        public static async Task<string> GetReportData<T>(string getUrl, string token = "")
        {
            try
            {
                var client = new RestClient(getUrl);
                var request = new RestRequest(Method.GET);
                if (!string.IsNullOrWhiteSpace(token))
                {
                    request.AddParameter("Authorization", "Bearer " + token, ParameterType.HttpHeader);
                }
                var response = await client.ExecuteTaskAsync<T>(request);
                return response.Content;
            }
            catch (Exception e)
            {
                return default;
            }
        }

        //private static string FormatUrl(object obj)
        //{
        //    string url = "";
        //    var type = obj.GetType();
        //    var properties = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        //    foreach (var property in properties)
        //    {
        //        var name = property.Name;
        //        name = name.ToLowerFirst();
        //        var value = property.GetValue(obj);
        //        url += $"{name}={value}&";
        //    }
        //    return url.Trim('&');
        //}

        //private static unsafe string ToLowerFirst(this string str)
        //{
        //    if (str == null) return null;
        //    string ret = string.Copy(str);
        //    fixed (char* ptr = ret)
        //        *ptr = char.ToLower(*ptr);
        //    return ret;
        //}
        /// <summary>
        /// 向webapi发送请求执行导入操作
        /// </summary>
        /// <param name="token">身份验证token</param>
        /// <param name="reauestUrl">api请求完整路径</param>
        /// <param name="bytes">文件byte[]</param>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        public static string PostImport(string reauestUrl, byte[] bytes, string fileName)
        {
            HttpClient httpClient = new HttpClient();
            //ByteArrayContent fileContent = new ByteArrayContent(bytes);
            //fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName };
            MultipartFormDataContent content = new MultipartFormDataContent();
            string result = "";

            using (var multipartFormDataContent = new MultipartFormDataContent())
            {
                var values = new[]
                                   {
                            new KeyValuePair<string, string>("webSite","HysEC.CustomersApp"),
                            new KeyValuePair<string, string>("index", "0"),
                            new KeyValuePair<string, string>("clearAllFiles", "0"),
                             new KeyValuePair<string, string>("autoUncompress", "1"),
                        };
                foreach (var keyValuePair in values)
                {
                    multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                        String.Format("\"{0}\"", keyValuePair.Key));
                }
                multipartFormDataContent.Add(new ByteArrayContent(bytes), "file", fileName);
                
                result = httpClient.PostAsync(reauestUrl, multipartFormDataContent).Result.Content.ReadAsStringAsync().Result;
            }


            //content.Add(fileContent);
            //var result = httpClient.PostAsync(reauestUrl, content);
            //return result.Result.Content.ReadAsStringAsync().Result;
            return result;
        }
    }
}
